package com.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.BaseResponse;
import com.common.ResultUtils;
import com.domain.entity.User;
import com.domain.entity.UserFriend;
import com.domain.entity.UserSession;
import com.service.UserFriendService;
import com.service.UserSessionService;
import com.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.List;

@RestController
@RequestMapping("/friend")
public class UserFriendController {

    @Autowired
    private UserFriendService userFriendService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private UserSessionService userSessionService;

    /**
     * 获取用户的好友列表
     *
     * @param httpServletRequest
     * @return
     */
    @GetMapping
    public BaseResponse<List<UserFriend>> getFriendList(HttpServletRequest httpServletRequest) {
        QueryWrapper<UserFriend> wrapper = new QueryWrapper<>();
        User loginUser = usersService.getLoginUser(httpServletRequest);
        wrapper.eq("user_id", loginUser.getId());
        List<UserFriend> friends = userFriendService.list(wrapper);
        if (CollectionUtil.isEmpty(friends)) {
            throw new RuntimeException("没有好友");
        }
        return ResultUtils.success(friends);
    }

    /**
     * 删除好友
     *
     * @param friendId
     * @param httpServletRequest
     * @return
     */
    @DeleteMapping("/{friendId")
    @Transactional
    public BaseResponse<Boolean> deleteFriend(@PathParam("friendId") Long friendId, HttpServletRequest httpServletRequest) {
        User loginUser = usersService.getLoginUser(httpServletRequest);
        QueryWrapper<UserFriend> userFriendQueryWrapper = new QueryWrapper<>();
        userFriendQueryWrapper.eq("friend_id", friendId).eq("user_id", loginUser.getId()).or(wrapper -> wrapper.eq("friend_id", loginUser.getId()).eq("user_id", friendId));
        //删除好友
        userFriendService.remove(userFriendQueryWrapper);
        //删除与好友之间的会话
        QueryWrapper<UserSession> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", loginUser.getId()).eq("session_id", friendId).or(wrapper1 -> wrapper1.eq("user_id", friendId).eq("session_id", loginUser.getId()));
        userSessionService.remove(wrapper);
        return ResultUtils.success(true);
    }

}
